import { FC, JSX } from 'react';
import {
  DndContext,
  closestCenter,
  useSensor,
  useSensors,
  MouseSensor,
  DragEndEvent,
} from '@dnd-kit/core';
import {
  SortableContext,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';

interface DragContainerProps {
  children: JSX.Element | JSX.Element[];
  items: { id: string; [k: string]: any }[];
  onDragEnd: (oldIndex: number, newIndex: number) => void;
}

const DragContainer: FC<DragContainerProps> = (props) => {
  const { children, items, onDragEnd } = props;

  const sensors = useSensors(
    useSensor(MouseSensor, {
      activationConstraint: { distance: 8 }, // 按下鼠标移动超过8xp才判断为是拖拽行为
    })
  );

  function handleDragEnd(e: DragEndEvent) {
    const { active, over } = e;
    if (over === null) return;

    if (active.id !== over.id) {
      const oldIndex = items.findIndex((item) => item.id === active.id);
      const newIndex = items.findIndex((item) => item.id === over.id);
      onDragEnd(oldIndex, newIndex);
    }
  }

  return (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCenter}
      onDragEnd={handleDragEnd}
    >
      <SortableContext items={items} strategy={verticalListSortingStrategy}>
        {children}
      </SortableContext>
    </DndContext>
  );
};

export default DragContainer;
